/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.server.connection;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 *
 */
public class ConnectionHandler {

    // protected PrintWriter _out;
    protected DataOutputStream outputStream;
    protected Socket socket;
    protected ReaderThread reader;
    protected InputStream inputStream;
    protected boolean isShutDown = false;
    private IConnectionListenner connectionListener;
    private WriterThread writerThread;

    public void setListener(IConnectionListenner listener) {
        connectionListener = listener;
    }

    public ConnectionHandler(Socket s, IConnectionListenner listener) throws IOException {
        connectionListener = listener;
        socket = s;
        outputStream = new DataOutputStream(s.getOutputStream());
        inputStream = s.getInputStream();
        reader = new ReaderThread(listener, inputStream);
        writerThread = new WriterThread(outputStream, socket);
    }
    public void setReaderName(String name)
    {
        reader.setThreadName(name);
    }

    public boolean sendMessage(String message) {
        if (writerThread == null) {
            return false;
        }
        return writerThread.queueMessage(message);
    }

    public void sendMessage(byte[] data) {
        writerThread.queueMessage(data);
    }

    public void sendImediate(String message) {
        writerThread.sendImediate(message);
    }

    public void stopConnection() {
        try {
            if (reader != null) {
                reader.stop();
            }
            if (writerThread != null) {
                writerThread.stop();
            }
            writerThread = null;
            reader = null;
            Runtime.getRuntime().gc();
        } catch (Exception ex) {
        }
    }
}
